const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const db = require('../db');
const { authenticateToken } = require('../middleware/authMiddleware');

// 用户注册
router.post('/register', (req, res) => {
  const { username, password, fullName, email, role } = req.body;

  // 验证必填字段
  if (!username || !password) {
    return res.status(400).json({ message: '用户名和密码是必填项' });
  }

  // 检查用户名是否已存在
  db.get('SELECT * FROM users WHERE username = ?', [username], (err, user) => {
    if (err) {
      return res.status(500).json({ message: '数据库错误', error: err.message });
    }

    if (user) {
      return res.status(400).json({ message: '用户名已存在' });
    }

    // 获取角色ID
    let roleIdQuery = 'SELECT id FROM roles WHERE name = ?';
    let roleParam = role === 'payment_manager' ? 'payment_manager' : 'employee'; // 默认员工角色

    db.get(roleIdQuery, [roleParam], (err, role) => {
      if (err) {
        return res.status(500).json({ message: '获取角色失败', error: err.message });
      }

      if (!role) {
        return res.status(400).json({ message: '无效的角色' });
      }

      // 密码加密
      const hashedPassword = bcrypt.hashSync(password, 10);

      // 创建新用户
      const sql = `INSERT INTO users (username, password, full_name, email, role_id)
                   VALUES (?, ?, ?, ?, ?)`;
      db.run(sql, [username, hashedPassword, fullName || '', email || '', role.id], function(err) {
        if (err) {
          return res.status(500).json({ message: '创建用户失败', error: err.message });
        }

        res.status(201).json({ message: '用户注册成功', userId: this.lastID });
      });
    });
  });
});

// 用户登录
router.post('/login', (req, res) => {
  const { username, password } = req.body;

  // 查找用户
  db.get(`SELECT u.id, u.username, u.password, u.full_name, u.email, r.name as role
          FROM users u
          JOIN roles r ON u.role_id = r.id
          WHERE u.username = ?`, [username], (err, user) => {
    if (err) {
      return res.status(500).json({ message: '数据库错误', error: err.message });
    }

    if (!user) {
      return res.status(401).json({ message: '用户名或密码不正确' });
    }

    // 验证密码
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      return res.status(401).json({ message: '用户名或密码不正确' });
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { id: user.id, username: user.username, role: user.role },
      process.env.JWT_SECRET || 'your_jwt_secret',
      { expiresIn: '8h' }
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        fullName: user.full_name,
        email: user.email,
        role: user.role
      }
    });
  });
});

// 获取当前登录用户信息
router.get('/me', authenticateToken, (req, res) => {
  db.get(`SELECT u.id, u.username, u.full_name, u.email, r.name as role
          FROM users u
          JOIN roles r ON u.role_id = r.id
          WHERE u.id = ?`, [req.user.id], (err, user) => {
    if (err) {
      return res.status(500).json({ message: '数据库错误', error: err.message });
    }

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.json({
      id: user.id,
      username: user.username,
      fullName: user.full_name,
      email: user.email,
      role: user.role
    });
  });
});

module.exports = router;